import axios from 'axios'
import type { InternalAxiosRequestConfig } from 'axios'
import store from '@/core/stores'
import { getToken } from '@/core/utils/auth'
import { toast } from '@/core/utils/tools'

const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
})

// 请求拦截器
request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  // header中添加请求拦截器
  const token = getToken()
  if (token) {
    config.headers['token'] = token
  }
  return config
})

// 响应拦截器
// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response.request.responseType === 'blob'
      ? response.data
      : response.data.data
  },
  function (error) {
    const msg = error.response.data.msg || '请求失败'

    if (msg === '非法token，请先登录！') {
      store.dispatch('logout').finally(() => location.reload())
      location.href = '/login'
    }

    toast(msg, 'error')

    return Promise.reject(error)
  }
)
export default request
